package com.dwy2002.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dwy2002.common.Result;
import com.dwy2002.common.utils.JwtUtil;
import com.dwy2002.enums.Status;
import com.dwy2002.pojo.po.users.RolePermission;
import com.dwy2002.pojo.po.users.RoleUser;
import com.dwy2002.pojo.po.users.Users;
import com.dwy2002.user.mapper.PermissionMapper;
import com.dwy2002.user.mapper.RolePermissionMapper;
import com.dwy2002.user.mapper.RoleUserMapper;
import com.dwy2002.user.service.IRolePermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.dwy2002.common.Result.fail;
import static com.dwy2002.common.Result.handleResult;
import static com.dwy2002.common.utils.Utils.getToken;

/**
 * @author 杜伟毅
 * @version 1.0
 * @since 2025/04/03
 */
@Service
@RequiredArgsConstructor
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {
    private final RoleUserMapper roleUserMapper;
    private final PermissionMapper permissionMapper;
    private final JwtUtil jwtUtil;

    /**
     * 删除关系权限代码（根据权限id）
     *
     * @param permIds 权限id集合
     * @author 杜伟毅
     * @since 2025/4/3 0003 22:44
     */
    @Override
    public void deleteRolePermissionByPermIds(List<String> permIds) {
        LambdaQueryWrapper<RolePermission> lqw = new LambdaQueryWrapper<>();
        lqw.in(RolePermission::getPermId, permIds);
        remove(lqw);
    }

    /**
     * 删除关系权限代码（根据角色id）
     *
     * @param roleId 角色id
     * @author 杜伟毅
     * @since 2025/4/3 0003 22:44
     */
    @Override
    public void deleteRolePermissionByRoleId(String roleId) {
        LambdaQueryWrapper<RolePermission> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RolePermission::getRoleId, roleId);
        remove(lqw);
    }

    /**
     * 授予权限
     *
     * @param permId 权限id
     * @author 杜伟毅
     * @since 2025/4/4 0004 10:34
     */
    @Override
    public Result<Void> grantPermission(String permId) {
        String userId = jwtUtil.parseToken(getToken(), Users.class).getId();

        //查询用户关联的角色ID
        String roleId = roleUserMapper
                .selectOne(new LambdaQueryWrapper<RoleUser>().eq(RoleUser::getUserId, userId))
                .getRoleId();

        if (ObjectUtils.isEmpty(permissionMapper.selectById(permId))) return fail(Status.BAD_REQUEST, "权限不存在");

        if (isRolePermissionDuplicate(roleId, permId)) return fail(Status.BAD_REQUEST, "角色已有该权限，请勿重复添加");

        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(roleId);
        rolePermission.setPermId(permId);


        boolean save = save(rolePermission);
        return Result.handleResult(save, "添加成功", "添加失败");
    }

    /**
     * 撤销权限
     *
     * @param permId 权限id
     * @author 杜伟毅
     * @since 2025/4/4 0004 10:56
     */
    @Override
    public Result<Void> revokePermission(String permId) {
        String userId = jwtUtil.parseToken(getToken(), Users.class).getId();

        //查询用户关联的角色ID
        String roleId = roleUserMapper
                .selectOne(new LambdaQueryWrapper<RoleUser>().eq(RoleUser::getUserId, userId))
                .getRoleId();

        if (ObjectUtils.isEmpty(permissionMapper.selectById(permId))) return fail(Status.BAD_REQUEST, "权限不存在");

        LambdaQueryWrapper<RolePermission> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RolePermission::getRoleId, roleId)
                .eq(RolePermission::getPermId, permId);
        boolean remove = remove(lqw);
        return handleResult(remove, "撤销成功", "撤销失败");
    }

    //子方法------------------------------------------------------------------------

    /**
     * 校验角色权限关系是否重复
     *
     * @param roleId 角色id
     * @param permId 权限id
     * @return true：重复 false：不重复
     * @author 杜伟毅
     * @since 2025/4/4 0004 17:55
     */
    private boolean isRolePermissionDuplicate(String roleId, String permId) {
        LambdaQueryWrapper<RolePermission> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RolePermission::getRoleId, roleId)
                .eq(RolePermission::getPermId, permId);
        return exists(lqw);
    }
}
